import pygame
from random import choice


class Ball(pygame.sprite.Sprite):

    def __init__(self, gray_image, green_image, position, speed, bg_size, target):
        pygame.sprite.Sprite.__init__(self)
        self.gray_image = pygame.image.load(gray_image).convert_alpha()
        self.green_image = pygame.image.load(green_image).convert_alpha()
        self.rect = self.gray_image.get_rect()
        self.rect.left, self.rect.top = position
        self.width, self.height = bg_size[0], bg_size[1]
        self.radius = self.rect.width / 2
        self.target = target
        self.control = False
        # 速度
        self.speed = speed
        # 方向
        self.side = [choice([-1, 1]), choice([-1, 1])]
        # 是否碰撞,如果碰撞则重新获取随机值
        self.collide = False

    def move(self):
        if self.control:
            self.rect = self.rect.move(self.speed)
        else:
            self.rect = self.rect.move(self.speed[0] * self.side[0],
                                       self.speed[1] * self.side[1])
        if self.rect.right <= 0:
            self.rect.left = self.width
        elif self.rect.left >= self.width:
            self.rect.right = 0
        elif self.rect.bottom <= 0:
            self.rect.top = self.height
        elif self.rect.top >= self.height:
            self.rect.bottom = 0

    def check(self, motion):
        if self.target < motion < self.target + 5:
            return True
        else:
            return False